﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Text;

namespace UsefulExtensionMethods
{
    public static class ObjectExtensions
    {
        public static string ToReflectedPropertyString(this object o)
        {
            StringBuilder sb1 = new StringBuilder();
            foreach (PropertyInfo pi in o.GetType().GetProperties())
            {
                sb1.AppendLine(String.Format("{0} : {1}", pi.Name, pi.GetValue(o, null)));
            }
            return sb1.ToString();
        }

        public static T Cast<T>(this object o)
        {
            if (o == null)
                throw new NullReferenceException();
            else
                return (T) Convert.ChangeType(o, typeof(T));
        }

        public static T Cast<T>(this object o, T defaultValue)
        {
            if (o == null)
                return defaultValue;
            else
                return (T)Convert.ChangeType(o, typeof(T));
        }
    }
}
